/**
 * Created by congzhang on 17/11/22.
 */


var http = require("http");
var mime = require("mime");
var url = require("url");
var fs = require("fs");
var formidable = require("formidable");
var path = require("path");
var querystring = require("querystring");
var express = require("express");
var bodyParser = require("body-parser");

// var fstream = require("fstream");
// var tar = require("tar");
// var zlib = require("zlib");

var exec = require('child_process').exec;


var app = express();
app.set("view engine", 'ejs');  // 设置模板引擎
// 将 post 请求的请求体转为对象
app.use(bodyParser.urlencoded({extended: true, uploadDir: "./temp"}));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, "statics"))); // 设置静态文件目录



app.get("/", function (req, res) {

    fs.createReadStream("index.html").pipe(res)
});


app.post("/", function (req, res) {

    console.log(req.body);
    var title = req.body["title"];
    var content = req.body["content"];

    title = title.split('\n');

    var timeStamp = new Date().getTime().toString();
    var dirPath = path.join('./statics/', '/temp/', timeStamp);
    console.log(dirPath);
    fs.mkdir(dirPath, function () {
        for (var i = 0; i < title.length; i ++){

            var filePath = path.join(dirPath, title[i] + '.txt');
            console.log(filePath);
            fs.writeFileSync(filePath, content)
        }

        // var zipName = dirPath + '.zip';
        var zipName = timeStamp + '.zip';

        var cmd = "/usr/bin/zip -r " + zipName + " " + timeStamp;
        console.log(cmd);
        exec(cmd, {cwd: __dirname + "/statics/temp"},function (err, stdout, stderr) {
            if(err) {
                console.log('get weather api error:'+stderr, err);
            } else {
                console.log(stdout);

                res.send({
                    "status": true,
                    "zipUrl": path.join('temp', timeStamp + '.zip')
                })
            }

        });


    });



});



app.listen(9102, "0.0.0.0");
console.log("http://0.0.0.0:9101");
